// pages/list/list.js
import api from '../../utils/fetch.js';
const app = getApp();
const {
  fetch
} = api;

Page({
  data: {
    id: '0',
    total: 0,
    params: {
      _page: 1,
      _limit: 5,
      q: ''
    },
    shoplist: [],
    isloading: false,
    loadtext: "疯狂的加载中。。。",
    newtitle: '假数据'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    app.setbackstatus(true);
    wx.showToast({
      title: '加载中...',
      mask: true,
      icon: 'loading'
    })
    this.init(options.id)
  },
  onUnload() {
    app.setbackstatus(false)
  },
  init(id) {
    wx.showNavigationBarLoading()
    fetch(`categories/${id}`)
      .then(res => {
        // setTimeout(()=>{
        this.setData({
          newtitle: res.data.name
        })
        // },1000)
        return fetch(`categories/${id}/shops`, this.data.params)
      })
      .then(res => {
        this.setData({
          total: res.header['X-Total-Count'],
          id,
          shoplist: res.data
        })
        wx.hideNavigationBarLoading()
        wx.hideToast()
      })
  },
  getq: function(e) {
    let {
      _limit,
      _page
    } = this.data.params;
    this.setData({
      params: {
        _limit,
        _page,
        q: e.detail.q
      }
    })
    this.searchcomfn()
  },
  onPullDownRefresh() {
    console.log("上拉！")
    let _limit = this.data.params._page * this.data.params._limit;
    fetch(`categories/${this.data.id}/shops`, {
        _page: 1,
        _limit,
        q: ''
      })
      .then(res => {
        console.log(res)
        this.setData({
          shoplist: res.data
        })
        wx.stopPullDownRefresh()
      })
  },
  onReachBottom() {
    console.log("下拉！")
    let f = Math.ceil(this.data.total / this.data.params._limit) >= ++this.data.params._page
    if (!f) {
      this.setData({
        isloading: true,
        params: this.data.params,
        loadtext: '到底了，已经没有数据了'
      })
      setTimeout(() => {
        this.setData({
          isloading: false
        })
      }, 1000)
      return
    }
    this.setData({
      isloading: true,
      params: this.data.params
    })
    fetch(`categories/${this.data.id}/shops`, this.data.params)
      .then(res => {
        console.log(res.data)
        let newarr = [];

        res.data = res.data.map(item => {
          if (!item.score) {
            item.score = '暂无！'
          }
          return item
        })
        this.data.shoplist = this.data.shoplist.concat(res.data)
        this.setData({
          isloading: false,
          shoplist: this.data.shoplist
        })
      })
  },
  searchcomfn() {
    this.init(this.data.id, this.data.params)
  }
})